import axios from 'axios';
import qs from "qs";
import errorCode from './errorCodeValues';
import router from '@/routes';

axios.interceptors.response.use(
    response =>{
        if(response.data&&response.data.errorCode){
            for(let key of Object.keys(errorCode)){
                if(key===response.data.errorCode){
                    console.log(`errorCode:${errorCode[key].errorCode};errorMsg:${errorCode[key].errorMsg}`);//注意！！这里不是单引号 '  而是 `
                   /* Toast({
                        message:errorCode[key].errorMsg,//错误信息
                        duration:1000
                    });*/
                   alert(errorCode[key].errorMsg);
                    if(errorCode[key].route){
                        setTimeout(function(){
                            router.push(errorCode[key].route);
                        },1500);
                    }
                    return response;
                }
            }
            /*Toast({
                message:'服务器出现故障...已提交管理员!',//错误信息
                duration:1000
            });*/
            alert('服务器出现故障...已提交管理员!');
            console.log('interceptors errorCode日志:');
            console.log(response.data);
        }

        return response;
    },
    error => {
        console.log(error);
    }
)

var SIGN_REGEXP = /([yMdhsm])(\1*)/g;
var DEFAULT_PATTERN = 'yyyy-MM-dd';
function padding(s, len) {
    var len = len - (s + '').length;
    for (var i = 0; i < len; i++) { s = '0' + s; }
    return s;
};

export default {
    //校验是否为手机号
    checkIsMobile(phoneNum) {
        var reg = /^(1[3|4|5|7|8])[\d]{9}$/;
        if (reg.test(phoneNum) == false) {
            return false;
        }
        return true;
    },
    //判断非空
    isValidate(obj) {
        return obj != null && obj != "" && obj != undefined;
    },

    //判断数组
    isValidateArr(arr){
        return arr != null && arr != undefined && arr.length>0;
    },
    //给字符串长度大于一个数字的该字符串后面加上...
    interceptStr(str,num){
        return (this.isValidate(str)&&str.length>num)?str.substring(0,num)+'...':str;
    },

    //将url里的参数解析成json对象
    convertUrlToJSON(urlData){
        let field = urlData.split('&');

        let res = {};
        for(let i=0,len=field.length;i<len;i++){
            let temp = field[i].split('=');
            res[temp[0]]=temp[1];
        }
        return res;
    },

    //发送post请求并解决中文乱码问题
    axiosPost(url, data) {
        axios.create({headers: {'content-type': 'application/x-www-form-urlencoded'}});
        data = qs.stringify(data);
        return axios.post(url, data);
    },

    //日期处理
    formatDate: {
        format: function (date, pattern) {
            pattern = pattern || DEFAULT_PATTERN;
            return pattern.replace(SIGN_REGEXP, function ($0) {
                switch ($0.charAt(0)) {
                    case 'y': return padding(date.getFullYear(), $0.length);
                    case 'M': return padding(date.getMonth() + 1, $0.length);
                    case 'd': return padding(date.getDate(), $0.length);
                    case 'w': return date.getDay() + 1;
                    case 'h': return padding(date.getHours(), $0.length);
                    case 'm': return padding(date.getMinutes(), $0.length);
                    case 's': return padding(date.getSeconds(), $0.length);
                }
            });
        },
        parse: function (dateString, pattern) {
            var matchs1 = pattern.match(SIGN_REGEXP);
            var matchs2 = dateString.match(/(\d)+/g);
            if (matchs1.length == matchs2.length) {
                var _date = new Date(1970, 0, 1);
                for (var i = 0; i < matchs1.length; i++) {
                    var _int = parseInt(matchs2[i]);
                    var sign = matchs1[i];
                    switch (sign.charAt(0)) {
                        case 'y': _date.setFullYear(_int); break;
                        case 'M': _date.setMonth(_int - 1); break;
                        case 'd': _date.setDate(_int); break;
                        case 'h': _date.setHours(_int); break;
                        case 'm': _date.setMinutes(_int); break;
                        case 's': _date.setSeconds(_int); break;
                    }
                }
                return _date;
            }
            return null;
        }

    }

};
